package com.whmnx.chitchat.http;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;


import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.whmnx.chitchat.constants.Constants;
import com.whmnx.chitchat.main.LoginActivity;
import com.whmnx.chitchat.utils.SPUtil;
import com.whmnx.chitchat.utils.UItils;
import com.whmnx.chitchat.view.CustomLoadingDialog;

import org.apache.commons.lang3.StringEscapeUtils;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 *
 * @author Administrator
 * @date 2016/3/1
 */
public class HttpClient {
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    private static final String RET_CODE = "Status";
    private static final String RET_CODE2 = "code";
    private static final String RESULT = "Result";
    private static final String MESSAGE = "Message";

    private static int errCode;
    private static int errCode2 = 0;
    private static int type;
    private static Handler handler = new Handler(Looper.getMainLooper());
    private static  HttpClient httpClient;
    private static OkHttpClient okHttpClient;
    private static String path_url,url;
    private static Request request;

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");


    public static synchronized OkHttpClient getInstance(){
        if(okHttpClient == null){
            okHttpClient = new OkHttpClient.Builder()
                    //  .addInterceptor(basicParamsInterceptor) // 添加公共参数拦截器
                    .addInterceptor(new LoggingInterceptor()) //添加okhttp日志拦截器
                    .connectTimeout(40, TimeUnit.SECONDS) //连接超时时间
                    .writeTimeout(40, TimeUnit.SECONDS) //读取超时时间
                    .readTimeout(40, TimeUnit.SECONDS) ////写入超时时间
                    .retryOnConnectionFailure(false)//连接不上是否重连,false不重连
                    .build();
        }
        return okHttpClient;
    }


    public static void postImg(final Context context, String url2, List<File> files, final CallBack callBack) {
        CustomLoadingDialog.show(context);
        String hose =  SPUtil.getString(Constants.HOSE);
        if (!TextUtils.isEmpty(hose)){
            url = url2.replace(Constants.HOST, hose);
            path_url = url;
        }else {
            url = url2;
            path_url = url;
        }

       /* MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("multipartFiles", file.getName(),
                        RequestBody.create(MediaType.parse("image/png"), file));*/

        MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
        multipartBodyBuilder.setType(MultipartBody.FORM);

        //遍历paths中所有图片绝对路径到builder，并约定key如“upload”作为后台接受多张图片的key
        if (files != null){
            for (File file : files) {
                multipartBodyBuilder.addFormDataPart("files", file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file));
            }
        }

        //构建请求体
        RequestBody requestBody = multipartBodyBuilder.build();
       // RequestBody requestBody = builder.build();
        Request request = new Request.Builder()
                .tag(context)
                .url(url)
                .post(requestBody)
                .build();

        getInstance().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onFailure(4, e.getLocalizedMessage());
                        CustomLoadingDialog.dismiss(context);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                type = 0;
                handlerResponse(context,response, callBack);
            }
        });
    }


    public static void postVideo(final Context context, String url, File file, final CallBack callBack) {
        CustomLoadingDialog.show(context);
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("videoFile", file.getName(),
                        RequestBody.create(MediaType.parse("video/mp4"), file));

        RequestBody requestBody = builder.build();
        Request request = new Request.Builder()
                .tag(context)
                .url(url)
                .post(requestBody)
                .build();

        getInstance().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onFailure(4, e.getLocalizedMessage());
                        CustomLoadingDialog.dismiss(context);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                type = 0;
                handlerResponse(context,response, callBack);
            }
        });
    }



    public  static void post(final Context context, String url2, Map<String, Object> params, final CallBack callBack) {
        if (!UItils.isNetWorkConnected()) {
            UItils.showToastSafe("网络已断开,请检查网络连接");
            return;
        }
        CustomLoadingDialog.show(context);
        String hose =  SPUtil.getString(Constants.HOSE);
        if (!TextUtils.isEmpty(hose)){
            url = url2.replace(Constants.HOST, hose);
            path_url = url;
        }else {
            url = url2;
            path_url = url;
        }
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, Object> map : params.entrySet()) {
            String key = map.getKey();
            String value;
            if (map.getValue() == null) {
                value = "";
            } else {
                value = (String) map.getValue();
            }
            builder.add(key, value);
        }
        RequestBody requestBody = builder.build();

         Logger.json(new Gson().toJson(params));
            request = new Request.Builder()
                    .tag(context)
                    .url(url)
                    .addHeader("Authorization", "Bearer " + SPUtil.getString(Constants.TOKEN))
                    .post(requestBody)
                    .build();


        getInstance().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onFailure(4, e.getLocalizedMessage());
                        CustomLoadingDialog.dismiss(context);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                handlerResponse(context,response, callBack);
            }
        });
    }


    public  static void post2(final Context context, String url2, Map<String, Object> params, final CallBack callBack) {
        if (!UItils.isNetWorkConnected()) {
            UItils.showToastSafe("网络已断开,请检查网络连接");
            return;
        }
        CustomLoadingDialog.show(context);
        String hose =  SPUtil.getString(Constants.HOSE);
        if (!TextUtils.isEmpty(hose)){
            url = url2.replace(Constants.HOST, hose);
            path_url = url;
        }else {
            url = url2;
            path_url = url;
        }
      /*  FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, Object> map : params.entrySet()) {
            String key = map.getKey();
            String value;
            if (map.getValue() == null) {
                value = "";
            } else {
                value = (String) map.getValue();
            }
            builder.add(key, value);
        }*/

        //表单提交 和 json 提交
        Gson gson = new Gson();
        String param = gson.toJson(params);
        RequestBody requestBody = RequestBody.create(JSON, param);

        Logger.json(new Gson().toJson(params));

      //  RequestBody requestBody = builder.build();

        Logger.json(new Gson().toJson(params));
        request = new Request.Builder()
                .tag(context)
                .url(url)
                .addHeader("Authorization", "Bearer" + SPUtil.getString(Constants.TOKEN))
                .post(requestBody)
                .build();


        getInstance().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onFailure(4, e.getLocalizedMessage());
                        CustomLoadingDialog.dismiss(context);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                handlerResponse(context,response, callBack);
            }
        });
    }



    public static void get(final Context context,String url2, Map<String, Object> map, final CallBack callBack) {  //13871503384
        if (!UItils.isNetWorkConnected()) {
            UItils.showToastSafe("网络已断开,请检查网络连接");
            return;
        }
        String hose =  SPUtil.getString(Constants.HOSE);
        if (!TextUtils.isEmpty(hose)){
            url = url2.replace(Constants.HOST, hose);
            path_url = url;
        }else {
            url = url2;
            path_url = url;
        }
        if (!url.contains(Constants.GETCHATRECORDLIST) && !url.contains(Constants.GETUPDATECHATRECORDSTATE) && !url.contains(Constants.GETSEARCHCHATRECORD)){
            CustomLoadingDialog.show(context);
        }


        if (map != null && map.size() >0) {
            url += "?";
            for (String key : map.keySet()) {
                String value = (String) map.get(key);
                url += key + "=" + value + "&";
            }
            url = url.substring(0, url.length() - 1);
        }

        // 去掉最后一个空格
        Logger.json(new Gson().toJson(map));
        Request request = new Request.Builder()
                .tag(context)
                .url(url)
                .addHeader("Authorization", "Bearer " + SPUtil.getString(Constants.TOKEN))
               // .addHeader("Connection", "close")
                .build();
        String finalUrl = url;
        //3,新建一个call对象
        //4，请求加入调度，这里是异步请求回调  enqueue
        //execute() 同步
        getInstance().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.onFailure(4, e.getLocalizedMessage());
                      //  callBack.onFailure(-1, e.getLocalizedMessage());
                    }
                });
            }

            @Override
            public void onResponse(final Call call, Response response) throws IOException {
                handlerResponse(context,response, callBack);
            }
        });
    }


    /**
     * 根据tag取消请求
     *
     * @param tag 标签
     */
    public static void cancelRequest(Object tag) {
        for (Call call : getInstance().dispatcher().queuedCalls()) {
            if (call.request().tag().equals(tag)) {
                call.cancel();
            }
        }
    }


    private static void handlerResponse(Context context, Response response, final CallBack callBack) throws IOException {
        //看清楚是response.body().string()不是response.body().toString()
        String json = response.body().string();
       // json = json.replace("\"", "");
        System.out.println("json==" + json);
        Logger.json(json);
        final String finalJson = json;
        //主线程 更新UI
        handler.post(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject jsonObject = new JSONObject(finalJson);
                    String className = context.getClass().getSimpleName();
                    if (path_url.contains(Constants.GETUPDATEHEADIMG)){
                        callBack.onSuccess(new Gson().fromJson(finalJson, callBack.type));
                        CustomLoadingDialog.dismiss(context);
                        return;
                    }
                   if (finalJson.contains(MESSAGE)) {
                        String msg = jsonObject.getString(MESSAGE);
                        if (path_url.contains(Constants.GETFORUMLIKES) || className.contains("LoginActivity")){
                            UItils.showToastSafe(msg);
                        }
                    }

                    int errCode = jsonObject.getInt(RET_CODE);
                    if (errCode == 1) {
                        if (finalJson.contains(RESULT)) {
                            String data = jsonObject.getString(RESULT);
                            callBack.onSuccess(new Gson().fromJson(data, callBack.type));
                        } else {
                            callBack.onSuccess(new Gson().fromJson(finalJson, callBack.type));
                        }
                    } else if (errCode == 401) {  //token 过期
                        Intent intent = new Intent(UItils.getContext(), LoginActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        UItils.getContext().startActivity(intent);
                    } else if (errCode == 0){
                        if (!finalJson.contains(MESSAGE)) return;
                        String msg = jsonObject.getString(MESSAGE);
                        UItils.showToastSafe(msg);
                    }

                    CustomLoadingDialog.dismiss(context);

                } catch (Exception e) {
                    e.printStackTrace();
                    callBack.onFailure(-1, e.getLocalizedMessage());
                    CustomLoadingDialog.dismiss(UItils.getContext());
                }
            }
        });
    }

    /**
     * 请求响应日志信息，方便debug
     */
    public static class LoggingInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            long t1 = System.nanoTime();
            Logger.i(String.format("Sending request %s on %s%n%s",
                    request.url(), chain.connection(), request.headers()));
            if (null != chain) {
                Response response = chain.proceed(request);
                long t2 = System.nanoTime();

                Logger.i(String.format("Received response for %s in %.1fms%n%s",
                        response.request().url(), (t2 - t1) / 1e6d, response.headers()));
                return response;
            }
            return null;
        }
    }
}
